#!/usr/bin/env python
""" This is a CLI script for getting all the details of a person
"""

from __future__ import print_function

import __main__
__main__.__requires__ = __requires__ = ["tahrir-api", "sqlalchemy>=0.7"]
import pkg_resources
pkg_resources.require(__requires__)

import json
import os
import sys

from tahrir_api.dbapi import TahrirDatabase

import fedmsg.config

import fedbadges.utils


def initialize():
    fm_config = fedmsg.config.load_config()
    uri = fm_config['badges_global']['database_uri']
    tahrir = TahrirDatabase(
        uri,
        notification_callback=fedbadges.utils.notification_callback,
    )
    return tahrir


def main():
    tahrir = initialize()
    nickname = os.getenv('SAR_USERNAME')
    if not nickname:
        print('An username is required to query datagrepper')
        return 1

    payload = {}
    person = tahrir.get_person(nickname=nickname)

    if not person:
        print('No such person %r' % nickname)
        return 1

    payload = {
        'id': person.id,
        'nickname': nickname,
        'email': person.email,
        'website': person.website,
        'bio': person.bio,
        'created_on': person.created_on.isoformat(),
        'last_login': person.last_login.isoformat()
        if person.last_login else 'unknown',
        'opt_out': person.opt_out,
        'rank': person.rank,
        'assertions': []
    }

    assertions = tahrir.get_assertions_by_email(person.email)

    if assertions:
        assertion_list = []
        for assertion in assertions:
            assertion_list.append({
                'badge_id': assertion.badge_id,
                'issued_on': assertion.issued_on.isoformat()
            })

        payload['assertions'] = assertion_list

    print(json.dumps(
        payload, sort_keys=True, indent=4, separators=(',', ': ')
    ).encode('utf-8'))


if __name__ == '__main__':
    sys.exit(main())

